﻿using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace CollectionOperationKit
{
    [Icon("pack://application:,,,/CollectionOperationKit;component/Resources/ArrayIcon.png")]
    [Category("对象与集合操作")]
    public class ServerSideArraySort : BaseServerCommand, ICommandExecutableInServerSide
    {


        /// <summary>
        /// 在设计器中展示的插件名称
        /// </summary>
        /// <returns>易读的字符串</returns>
        public override string ToString()
        {

            if (String.IsNullOrEmpty(OutParamaterName))
            {
                return "数组排序"; // 命令列表中默认显示的名称
            }
            else
            {
                return "数组排序：" + OutParamaterName;
            }
        }

        [OrderWeight(100)]
        [DisplayName("输入参数（数组）")]
        [FormulaProperty]
        [Description("操作可能不会影响【输入参数】中用到的变量，如需对变量进行修改，可将其填写到【将结果返回到变量】。")]
        public object InParamater { get; set; }


        [OrderWeight(103)]
        [DisplayName("点击设置排序规则")]
        [ListProperty]
        public List<SortRuleObject> SortRulePairs { get; set; } = new List<SortRuleObject>();


        public ExecuteResult Execute(IServerCommandExecuteContext dataContext)
        {
            ArrayList data = getArrayListParam(dataContext, this.InParamater);
            var source = data.Cast<object>();

            foreach (SortRuleObject sortRule in SortRulePairs.Reverse<SortRuleObject>())
            {
                string propertyName = (string)getParamValue(dataContext, sortRule.Name, false);

                if (sortRule.Direction == Direction.升序)
                {
                    source = source.OrderBy(d => ServerSideHelpers.GetObjectPropertyForSorting(d, propertyName));
                }
                else
                {
                    source = source.OrderByDescending(d => ServerSideHelpers.GetObjectPropertyForSorting(d, propertyName));
                }
            }

            var result = new ArrayList(source.ToArray());

            returnToParam(dataContext, result);
            return new ExecuteResult();
        }

    }
}
